package xin.alum.aim.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import com.google.protobuf.GeneratedMessageV3;

import java.io.IOException;

public class ProtoSerializer extends StdScalarSerializer<GeneratedMessageV3> {

    public ProtoSerializer() {
        super(GeneratedMessageV3.class);
    }

    @Override
    public void serialize(GeneratedMessageV3 generatedMessageV3, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        serialize(generatedMessageV3, jsonGenerator, serializerProvider, false);
    }

    public void serialize(GeneratedMessageV3 value, JsonGenerator gen, SerializerProvider provider, boolean isProperty) throws IOException {
        byte[] bytes = value.toByteArray();
        gen.writeStartArray();
        if (!isProperty) {
            //通过这个找到对应的反序列化器
            gen.writeString(GeneratedMessageV3.class.getName());
        }
        //记录具体类型
        gen.writeString(value.getClass().getName());
        gen.writeBinary(bytes);
        gen.writeEndArray();
    }

    @Override
    public void serializeWithType(GeneratedMessageV3 value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException {
        //对外一律以父类 GeneratedMessageV3 显示类型
        WritableTypeId typeId = typeSer.typeId(value, GeneratedMessageV3.class, JsonToken.VALUE_STRING);
        WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeId);

        serialize(value, g, provider, true);
        typeSer.writeTypeSuffix(g, typeIdDef);
    }

}
